use crate::common::error_enum::ErrorEnum::{self, *};

use crate::pcap_parse::pcap_file::{PcapFile, parse_u16, parse_u32};
use crate::pcap_parse::pcap_hdr::Endianness::BigEndian;
use crate::pcap_parse::pcap_hdr::*;
use crate::utils::format_data_as_lines;
use log::info;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::io::{Read, Seek, SeekFrom};

const ETHERNET_HEADER_LEN: usize = 14;
const IPV4_HEADER_LEN: usize = 20;
const IPV6_HEADER_LEN: usize = 40;
const TCP_HEADER_LEN: usize = 20;
const UDP_HEADER_LEN: usize = 8;

const ICMP_HEADER_LEN: usize = 8;
const DNS_HEADER_LEN: usize = 12;
const ARP_V4_HEADER_LEN: usize = 28;

const MAC_ADDR_LEN: usize = 6;
const IPV4ADDR_LEN: usize = 4;
const IPV6ADDR_LEN: usize = 16;

trait FromPcap {
    type Header;

    // header_len is meaningless in Enum Header ，flag is meaningless in actual Header
    fn from_pcap(
        flag: isize,
        pcap_index: usize,
        pcap_file: &mut PcapFile,
        offset: usize,
        header_len: usize,
    ) -> Result<Self::Header, ErrorEnum> {
        let single_pcap = pcap_file.get_single_pcap_mut(pcap_index)?;
        let index = single_pcap.index as u64;

        let pcap_file_buf = &mut pcap_file.pcap_file_buf;

        pcap_file_buf.seek(SeekFrom::Start(index + offset as u64))?;

        let mut buf = vec![0; header_len];
        pcap_file_buf.read_exact(&mut buf)?;
        Self::from_bytes(&buf)
    }
    fn from_bytes(buf: &Vec<u8>) -> Result<Self::Header, ErrorEnum>;
}

#[derive(Hash, Eq, PartialEq)]
pub enum EtherType {
    Ipv4 = 0x0800,
    Ipv6 = 0x86DD,
    Arp = 0x0806,
    Other = -1,
}
impl fmt::Display for EtherType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            EtherType::Ipv4 => write!(f, "IPv4"),
            EtherType::Ipv6 => write!(f, "IPv6"),
            EtherType::Arp => write!(f, "ARP"),
            EtherType::Other => write!(f, "Other"),
        }
    }
}

impl EtherType {
    pub fn new(num: isize) -> Self {
        match num {
            0x0800 => Self::Ipv4,
            0x86DD => Self::Ipv6,
            0x0806 => Self::Arp,
            _ => Self::Other,
        }
    }
}

#[derive(Hash, Eq, PartialEq)]
pub enum TransportType {
    Tcp = 6,
    Udp = 17,
    Other = -1,
}

impl fmt::Display for TransportType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            TransportType::Tcp => write!(f, "TCP"),
            TransportType::Udp => write!(f, "UDP"),
            TransportType::Other => write!(f, "Other"),
        }
    }
}
impl TransportType {
    pub fn new(num: isize) -> Self {
        match num {
            6 => Self::Tcp,
            17 => Self::Udp,
            _ => Self::Other,
        }
    }
}

#[derive(Hash, Eq, PartialEq)]
pub enum ApplicationType {
    Http = 80,
    Https = 8080,
    Other = -1,
}

impl fmt::Display for ApplicationType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ApplicationType::Http => write!(f, "HTTP"),
            ApplicationType::Https => write!(f, "HTTPS"),
            ApplicationType::Other => write!(f, "Other"),
        }
    }
}
impl ApplicationType {
    pub fn new(num: isize) -> Self {
        match num {
            80 => Self::Http,
            8080 => Self::Https,
            _ => Self::Other,
        }
    }
}

#[derive(Hash, Eq, PartialEq)]
pub enum IpAddr {
    V4(Ipv4Addr),
    V6(Ipv6Addr),
    Other(isize),
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct MacAddr {
    pub mac: [u8; 6],
}

impl fmt::Display for MacAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
            self.mac[0], self.mac[1], self.mac[2], self.mac[3], self.mac[4], self.mac[5]
        )
    }
}

impl MacAddr {
    fn new(buf: Vec<u8>) -> Result<MacAddr, ErrorEnum> {
        let mac: [u8; 6] = buf.try_into().map_err(|v: Vec<u8>| {
            ConvertVecToArrayError(format!("Expected 16, got {}", v.len()))
        })?;
        Ok(Self { mac })
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct Ipv4Addr {
    ip_addr: [u8; 4],
}

impl fmt::Display for Ipv4Addr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}.{}.{}.{}",
            self.ip_addr[0], self.ip_addr[1], self.ip_addr[2], self.ip_addr[3]
        )
    }
}

impl Ipv4Addr {
    fn new(buf: Vec<u8>) -> Result<Ipv4Addr, ErrorEnum> {
        let ip_addr: [u8; 4] = buf
            .try_into()
            .map_err(|v: Vec<u8>| ConvertVecToArrayError(format!("Expected 4, got {}", v.len())))?;
        Ok(Self { ip_addr })
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct Ipv6Addr {
    ip_addr: [u8; 16],
}

impl fmt::Display for Ipv6Addr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:02X}{:02X}:{:02X}{:02X}:{:02X}{:02X}:{:02X}{:02X}:{:02X}{:02X}:{:02X}:{:02X}:{:02X}{:02X}:{:02X}:{:02X}",
            self.ip_addr[0],
            self.ip_addr[1],
            self.ip_addr[2],
            self.ip_addr[3],
            self.ip_addr[4],
            self.ip_addr[5],
            self.ip_addr[6],
            self.ip_addr[7],
            self.ip_addr[8],
            self.ip_addr[9],
            self.ip_addr[10],
            self.ip_addr[11],
            self.ip_addr[12],
            self.ip_addr[13],
            self.ip_addr[14],
            self.ip_addr[15]
        )
    }
}

impl Ipv6Addr {
    fn new(buf: Vec<u8>) -> Result<Ipv6Addr, ErrorEnum> {
        let ip_addr: [u8; 16] = buf.try_into().map_err(|v: Vec<u8>| {
            ConvertVecToArrayError(format!("Expected 16, got {}", v.len()))
        })?;
        Ok(Self { ip_addr })
    }
}

#[derive(Debug, Clone)]
pub struct EthernetHeader {
    pub dst_mac: MacAddr, // 目标MAC地址
    pub src_mac: MacAddr, // 源MAC地址
    pub ether_type: u16,  // 以太网类型 (IPv4: 0x0800, IPv6: 0x86DD, Arp 0x0806)
}

impl fmt::Display for EthernetHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "Ethernet II, Src: {}, Dst: {}",
            self.src_mac, self.dst_mac
        )?;
        writeln!(f, "    Type: {}", EtherType::new(self.ether_type as isize))?;
        Ok(())
    }
}

impl FromPcap for EthernetHeader {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        if buf.len() != ETHERNET_HEADER_LEN {
            return Err(LengthError(String::from(format!(
                "Expected Ethernet Header len {} ,but get {}",
                ETHERNET_HEADER_LEN,
                buf.len()
            ))));
        }
        let ether_type = parse_u16([buf[12], buf[13]], Endianness::BigEndian);
        Ok(Self {
            dst_mac: MacAddr::new(buf[0..6].into())?,
            src_mac: MacAddr::new(buf[6..12].into())?,
            ether_type: ether_type,
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct ArpIpv4Header {
    pub hardware_type: u16,  // 硬件类型，以太网为 1
    pub protocol_type: u16,  // 协议类型，IPv4 为 0x0800
    pub hardware_length: u8, // 硬件地址长度，以太网为 6
    pub protocol_length: u8, // 协议地址长度，IPv4 为 4
    pub operation: u16,      // 操作类型，1 表示 ARP 请求，2 表示 ARP 响应
    pub sender_mac: MacAddr, // 发送端 MAC 地址
    pub sender_ip: Ipv4Addr, // 发送端 IP 地址
    pub target_mac: MacAddr, // 目标 MAC 地址
    pub target_ip: Ipv4Addr, // 目标 IP 地址
}

impl fmt::Display for ArpIpv4Header {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "Address Resolution Protocol (ARP)")?;
        writeln!(f, "    Hardware type: 0x{:04X}", self.hardware_type)?;
        writeln!(f, "    Protocol type: 0x{:04X}", self.protocol_type)?;
        writeln!(
            f,
            "    Hardware size: {} bytes, Protocol size: {} bytes",
            self.hardware_length, self.protocol_length
        )?;
        writeln!(
            f,
            "    Operation: {}",
            if self.operation == 1 {
                "Request"
            } else {
                "Reply"
            }
        )?;
        writeln!(
            f,
            "    Sender MAC: {}, Sender IP: {}",
            self.sender_mac, self.sender_ip
        )?;
        writeln!(
            f,
            "    Target MAC: {}, Target IP: {}",
            self.target_mac, self.target_ip
        )?;
        Ok(())
    }
}

impl FromPcap for ArpIpv4Header {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        if buf.len() != ARP_V4_HEADER_LEN {
            return Err(LengthError(String::from(format!(
                "Expected IPv4 len {} ,but get {}",
                ARP_V4_HEADER_LEN,
                buf.len()
            ))));
        }
        Ok(ArpIpv4Header {
            hardware_type: parse_u16([buf[0], buf[1]], Endianness::BigEndian), // 字节0：版本+头长度
            protocol_type: parse_u16([buf[2], buf[3]], Endianness::BigEndian), // 字节1：服务类型
            hardware_length: buf[4],
            protocol_length: buf[5],
            operation: parse_u16([buf[6], buf[7]], Endianness::BigEndian),
            sender_mac: MacAddr::new(buf[8..14].into())?, // 发送端 MAC 地址
            sender_ip: Ipv4Addr::new(buf[14..18].into())?, // 发送端 IP 地址
            target_mac: MacAddr::new(buf[18..24].into())?, // 目标 MAC 地址
            target_ip: Ipv4Addr::new(buf[24..28].into())?, // 目标 IP 地址
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Ipv4Header {
    pub version_ihl: u8,        // 版本(4bit) + 头长度(4bit)
    pub tos: u8,                // 服务类型
    pub total_len: u16,         // 总长度
    pub id: u16,                // 标识符
    pub flags_frag_offset: u16, // 标志(3bit) + 片偏移(13bit)
    pub ttl: u8,                // 生存时间
    pub protocol: u8,           // 协议 (TCP:6, UDP:17)
    pub checksum: u16,          // 头校验和
    pub src_addr: Ipv4Addr,     // 源IP地址
    pub dst_addr: Ipv4Addr,     // 目标IP地址
}

impl FromPcap for Ipv4Header {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        if buf.len() != IPV4_HEADER_LEN {
            return Err(LengthError(String::from(format!(
                "Expected IPv4 len {} ,but get {}",
                IPV4_HEADER_LEN,
                buf.len()
            ))));
        }
        Ok(Ipv4Header {
            version_ihl: buf[0], // 字节0：版本+头长度
            tos: buf[1],         // 字节1：服务类型
            total_len: parse_u16([buf[2], buf[3]], Endianness::BigEndian),
            id: parse_u16([buf[4], buf[5]], Endianness::BigEndian),
            flags_frag_offset: parse_u16([buf[6], buf[7]], Endianness::BigEndian),
            ttl: buf[8],      // 字节8：TTL
            protocol: buf[9], // 字节9：协议
            checksum: parse_u16([buf[10], buf[11]], Endianness::BigEndian),
            // 提取4字节地址并转换为Ipv4Addr类型
            src_addr: Ipv4Addr::new(buf[12..16].into())?,
            dst_addr: Ipv4Addr::new(buf[16..20].into())?,
        })
    }
}

impl fmt::Display for Ipv4Header {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "Internet Protocol Version 4, Src: {}, Dst: {}",
            self.src_addr, self.dst_addr
        )?;
        writeln!(
            f,
            "    Version: {}, Header Length: {} bytes",
            (self.version_ihl >> 4) & 0x0F,
            self.get_header_len()
        )?;
        writeln!(f, "    Differentiated Services Field: 0x{:02X}", self.tos)?;
        writeln!(f, "    Total Length: {}", self.total_len)?;
        writeln!(f, "    Identification: 0x{:04X}", self.id)?;
        writeln!(f, "    Flags: 0x{:04X}", self.flags_frag_offset & 0xE000)?;
        writeln!(
            f,
            "    Fragment Offset: {}",
            self.flags_frag_offset & 0x1FFF
        )?;
        writeln!(f, "    Time to Live: {}", self.ttl)?;
        writeln!(
            f,
            "    Protocol: {}",
            TransportType::new(self.get_protocol() as isize)
        )?;
        writeln!(f, "    Header Checksum: 0x{:04X}", self.checksum)?;
        Ok(())
    }
}

impl Ipv4Header {
    pub fn get_protocol(&self) -> u8 {
        self.protocol
    }
    pub fn get_header_len(&self) -> usize {
        let ihl = self.version_ihl & 0x0F;
        ihl as usize * 4 //头部长度字段（IHL）表示的是32位字的数量，而不是字节数
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Ipv6Header {
    pub version_tc_flow: [u8; 4], // 版本(4bit) + 流量类别(8bit) + 流标签(20bit)
    pub payload_len: u16,         // 有效载荷长度
    pub next_header: u8,          // 下一个头部
    pub hop_limit: u8,            // 跳数限制
    pub src_addr: Ipv6Addr,       // 源IPv6地址
    pub dst_addr: Ipv6Addr,       // 目标IPv6地址
}

impl fmt::Display for Ipv6Header {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "Internet Protocol Version 6, Src: {}, Dst: {}",
            self.src_addr, self.dst_addr
        )?;
        writeln!(
            f,
            "    Version: 6, Traffic Class: 0x{:02X}, Flow Label: 0x{:04X}",
            self.version_tc_flow[1],
            ((self.version_tc_flow[2] as u16) << 8) | self.version_tc_flow[3] as u16
        )?;
        writeln!(f, "    Payload Length: {}", self.payload_len)?;
        writeln!(
            f,
            "    Next Header: {}",
            TransportType::new(self.get_protocol() as isize)
        )?;
        writeln!(f, "    Hop Limit: {}", self.hop_limit)?;
        Ok(())
    }
}

impl FromPcap for Ipv6Header {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        // 验证缓冲区长度
        if buf.len() != IPV6_HEADER_LEN {
            return Err(LengthError(format!(
                "Expected IPv6 header length {}, got {}",
                IPV6_HEADER_LEN,
                buf.len()
            )));
        }

        Ok(Ipv6Header {
            // 前4字节直接作为数组
            version_tc_flow: [buf[0], buf[1], buf[2], buf[3]],

            // 2字节大端序有效载荷长度
            payload_len: parse_u16([buf[4], buf[5]], Endianness::BigEndian),

            next_header: buf[6], // 下一头部类型
            hop_limit: buf[7],   // 跳数限制
            src_addr: Ipv6Addr::new(buf[8..24].into())?,
            dst_addr: Ipv6Addr::new(buf[24..40].into())?,
        })
    }
}

impl Ipv6Header {
    pub fn get_protocol(&self) -> u8 {
        self.next_header
    }
    pub fn get_header_len(&self) -> usize {
        IPV6_HEADER_LEN
    }
}

#[derive(Debug, Clone, Copy)]
pub struct TcpHeader {
    pub src_port: u16,          // 源端口
    pub dst_port: u16,          // 目标端口
    pub seq_num: u32,           // 序列号
    pub ack_num: u32,           // 确认号
    pub data_offset_flags: u16, // 数据偏移(4bit) + 保留(6bit) + 标志(6bit)
    pub window: u16,            // 窗口大小
    pub checksum: u16,          // 校验和
    pub urgent_ptr: u16,        // 紧急指针
}

impl fmt::Display for TcpHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "Transmission Control Protocol, Src Port: {}, Dst Port: {}",
            self.src_port, self.dst_port
        )?;
        writeln!(f, "    Sequence number: {}", self.seq_num)?;
        writeln!(f, "    Acknowledgment number: {}", self.ack_num)?;
        writeln!(f, "    Header length: {} bytes", self.get_header_len())?;
        let (urg, ack, psh, rst, syn, fin) = self.flags();
        writeln!(
            f,
            "    Flags: 0x{:04X} [{}{}{}{}{}{}]",
            self.data_offset_flags & 0x003F,
            if urg { "URG " } else { "" },
            if ack { "ACK " } else { "" },
            if psh { "PSH " } else { "" },
            if rst { "RST " } else { "" },
            if syn { "SYN " } else { "" },
            if fin { "FIN " } else { "" }
        )?;
        writeln!(f, "    Window: {}", self.window)?;
        writeln!(f, "    Checksum: 0x{:04X}", self.checksum)?;
        writeln!(f, "    Urgent pointer: {}", self.urgent_ptr)?;
        Ok(())
    }
}

impl FromPcap for TcpHeader {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        if buf.len() < TCP_HEADER_LEN {
            return Err(LengthError(format!(
                "Expected TCP header length {}, got {}",
                TCP_HEADER_LEN,
                buf.len()
            )));
        }

        Ok(TcpHeader {
            src_port: parse_u16([buf[0], buf[1]], Endianness::BigEndian),
            dst_port: parse_u16([buf[2], buf[3]], Endianness::BigEndian),
            seq_num: parse_u32([buf[4], buf[5], buf[6], buf[7]], Endianness::BigEndian),
            ack_num: parse_u32([buf[8], buf[9], buf[10], buf[11]], Endianness::BigEndian),
            data_offset_flags: parse_u16([buf[12], buf[13]], Endianness::BigEndian),
            window: parse_u16([buf[14], buf[15]], Endianness::BigEndian),
            checksum: parse_u16([buf[16], buf[17]], Endianness::BigEndian),
            urgent_ptr: parse_u16([buf[18], buf[19]], Endianness::BigEndian),
        })
    }
}

impl TcpHeader {
    pub fn get_header_len(&self) -> usize {
        ((self.data_offset_flags >> 12) * 4) as usize
    }

    // 辅助方法：提取TCP标志位
    pub fn flags(&self) -> (bool, bool, bool, bool, bool, bool) {
        (
            (self.data_offset_flags & 0x0020) != 0, // URG
            (self.data_offset_flags & 0x0010) != 0, // ACK
            (self.data_offset_flags & 0x0008) != 0, // PSH
            (self.data_offset_flags & 0x0004) != 0, // RST
            (self.data_offset_flags & 0x0002) != 0, // SYN
            (self.data_offset_flags & 0x0001) != 0, // FIN
        )
    }
}

#[derive(Debug, Clone, Copy)]
pub struct UdpHeader {
    pub src_port: u16, // 源端口
    pub dst_port: u16, // 目标端口
    pub length: u16,   // 长度
    pub checksum: u16, // 校验和
}
impl fmt::Display for UdpHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "User Datagram Protocol, Src Port: {}, Dst Port: {}",
            self.src_port, self.dst_port
        )?;
        writeln!(f, "    Length: {}", self.length)?;
        writeln!(f, "    Checksum: 0x{:04X}", self.checksum)?;
        Ok(())
    }
}

impl FromPcap for UdpHeader {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        if buf.len() < UDP_HEADER_LEN {
            return Err(LengthError(format!(
                "Expected UDP header length {}, got {}",
                UDP_HEADER_LEN,
                buf.len()
            )));
        }

        Ok(UdpHeader {
            src_port: parse_u16([buf[0], buf[1]], Endianness::BigEndian),
            dst_port: parse_u16([buf[2], buf[3]], Endianness::BigEndian),
            length: parse_u16([buf[4], buf[5]], Endianness::BigEndian),
            checksum: parse_u16([buf[6], buf[7]], Endianness::BigEndian),
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct IcmpHeader {
    pub icmp_type: u8,     // 类型字段
    pub code: u8,          // 代码字段
    pub checksum: u16,     // 校验和
    pub identifier: u16,   // 标识符
    pub sequence_num: u16, // 序列号
}

impl fmt::Display for IcmpHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "Internet Control Message Protocol")?;
        writeln!(f, "    Type: {}, Code: {}", self.icmp_type, self.code)?;
        writeln!(f, "    Checksum: 0x{:04X}", self.checksum)?;
        writeln!(
            f,
            "    Identifier: 0x{:04X}, Sequence number: 0x{:04X}",
            self.identifier, self.sequence_num
        )?;
        Ok(())
    }
}

impl FromPcap for IcmpHeader {
    type Header = Self;

    fn from_bytes(buf: &Vec<u8>) -> Result<Self::Header, ErrorEnum> {
        if buf.len() < ICMP_HEADER_LEN {
            return Err(LengthError(format!(
                "Expected TCP header length {}, got {}",
                ICMP_HEADER_LEN,
                buf.len()
            )));
        }
        Ok(Self {
            icmp_type: buf[0],
            code: buf[1],
            checksum: parse_u16([buf[2], buf[3]], BigEndian),
            identifier: parse_u16([buf[4], buf[5]], BigEndian),
            sequence_num: parse_u16([buf[6], buf[7]], Endianness::BigEndian),
        })
    }
}

impl IcmpHeader {
    pub fn header_len(&self) -> usize {
        ICMP_HEADER_LEN
    }
}

#[derive(Debug, Clone)]
pub struct HttpHeader {
    pub method: String,                 // 请求方法 (GET, POST等)
    pub path: String,                   // 请求路径
    pub version: String,                // HTTP版本
    pub headers: Vec<(String, String)>, // 键值对格式的头部
}

impl fmt::Display for HttpHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "Hypertext Transfer Protocol")?;
        writeln!(f, "    {} {} {}", self.method, self.path, self.version)?;
        for (key, value) in &self.headers {
            writeln!(f, "    {}: {}", key, value)?;
        }
        Ok(())
    }
}

impl FromPcap for HttpHeader {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        // 将字节切片转为字符串
        let text = match std::str::from_utf8(buf) {
            Ok(s) => s,
            Err(_) => return Err(HttpParseError("Invalid UTF-8 in HTTP".into())),
        };

        // 分割为行
        let mut lines = text.lines();

        // 解析起始行
        let start_line = lines
            .next()
            .ok_or(HttpParseError("Empty HTTP header".into()))?;

        let parts: Vec<&str> = start_line.split_whitespace().collect();
        if parts.len() < 3 {
            return Err(HttpParseError("Invalid HTTP start line".into()));
        }

        let method = parts[0].to_string();
        let path = parts[1].to_string();
        let version = parts[2].to_string();

        // 解析头字段
        let mut headers = Vec::new();
        for line in lines {
            if line.is_empty() {
                break;
            } // 空行结束头部

            if let Some(colon_idx) = line.find(':') {
                let key = line[..colon_idx].trim().to_string();
                let value = line[colon_idx + 1..].trim().to_string();

                headers.push((key, value));
            }
        }

        Ok(HttpHeader {
            method,
            path,
            version,
            headers,
        })
    }
}

impl HttpHeader {
    /// 获取HTTP头部的总长度（包括结束标记）
    pub fn get_header_len(&self) -> usize {
        // 计算起始行长度
        let start_line_len = format!("{} {} {}\r\n", self.method, self.path, self.version).len();

        // 计算各头字段长度
        let headers_len = self
            .headers
            .iter()
            .map(|(k, v)| format!("{}: {}\r\n", k, v).len())
            .sum::<usize>();
        if start_line_len + headers_len == 0 {
            return 0;
        }

        // 添加结束标记长度
        start_line_len + headers_len + 2 // \r\n
    }
}

#[derive(Debug, Clone, Copy)]
pub struct DnsHeader {
    pub id: u16,         // 事务ID
    pub flags: u16,      // 标志位
    pub questions: u16,  // 问题数
    pub answers: u16,    // 回答数
    pub authority: u16,  // 授权资源记录数
    pub additional: u16, // 附加资源记录数
}

impl fmt::Display for DnsHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "Domain Name System (DNS)")?;
        writeln!(f, "    Transaction ID: 0x{:04X}", self.id)?;
        writeln!(
            f,
            "    Flags: 0x{:04X} [{}]",
            self.flags,
            if self.is_response() {
                "Response"
            } else {
                "Query"
            }
        )?;
        writeln!(f, "    Questions: {}", self.questions)?;
        writeln!(f, "    Answers: {}", self.answers)?;
        writeln!(f, "    Authority Records: {}", self.authority)?;
        writeln!(f, "    Additional Records: {}", self.additional)?;
        Ok(())
    }
}

impl FromPcap for DnsHeader {
    type Header = Self;
    fn from_bytes(buf: &Vec<u8>) -> Result<Self, ErrorEnum> {
        if buf.len() < DNS_HEADER_LEN {
            return Err(LengthError(format!(
                "Expected DNS header length {}, got {}",
                DNS_HEADER_LEN,
                buf.len()
            )));
        }

        Ok(DnsHeader {
            id: parse_u16([buf[0], buf[1]], Endianness::BigEndian),
            flags: parse_u16([buf[2], buf[3]], Endianness::BigEndian),
            questions: parse_u16([buf[4], buf[5]], Endianness::BigEndian),
            answers: parse_u16([buf[6], buf[7]], Endianness::BigEndian),
            authority: parse_u16([buf[8], buf[9]], Endianness::BigEndian),
            additional: parse_u16([buf[10], buf[11]], Endianness::BigEndian),
        })
    }
}

impl DnsHeader {
    // 辅助方法：判断是否为响应
    pub fn is_response(&self) -> bool {
        (self.flags & 0x8000) != 0
    }

    // 辅助方法：获取操作码
    pub fn opcode(&self) -> u8 {
        ((self.flags & 0x7800) >> 11) as u8
    }
}

#[derive(Debug, Clone, Copy)]
// IP层协议枚举
pub enum IpHeader {
    V4(Ipv4Header),
    V6(Ipv6Header),
    ArpV4(ArpIpv4Header),
    Other(isize),
}

impl fmt::Display for IpHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            IpHeader::V4(header) => write!(f, "{}", header),
            IpHeader::V6(header) => write!(f, "{}", header),
            IpHeader::ArpV4(header) => write!(f, "{}", header),
            _ => writeln!(f, ""),
        }
    }
}

impl FromPcap for IpHeader {
    type Header = Self;
    fn from_pcap(
        flag: isize,
        pcap_index: usize,
        pcap_file: &mut PcapFile,
        offset: usize,
        header_len: usize,
    ) -> Result<Self, ErrorEnum> {
        let flag_type = EtherType::new(flag);
        match flag_type {
            // IPv4
            EtherType::Ipv4 => {
                let ipv4_header =
                    Ipv4Header::from_pcap(0, pcap_index, pcap_file, offset, IPV4_HEADER_LEN)?;
                Ok(IpHeader::V4(ipv4_header))
            }
            // IPv6
            EtherType::Ipv6 => {
                let ipv6_header =
                    Ipv6Header::from_pcap(0, pcap_index, pcap_file, offset, IPV6_HEADER_LEN)?;
                Ok(IpHeader::V6(ipv6_header))
            }
            // ARP v4
            EtherType::Arp => {
                let arp_ipv4_header =
                    ArpIpv4Header::from_pcap(0, pcap_index, pcap_file, offset, ARP_V4_HEADER_LEN)?;
                Ok(IpHeader::ArpV4(arp_ipv4_header))
            }
            EtherType::Other => Ok(IpHeader::Other(flag)),
        }
    }

    fn from_bytes(buf: &Vec<u8>) -> Result<Self::Header, ErrorEnum> {
        todo!()
    }
}

impl IpHeader {
    fn get_header_len(&self) -> usize {
        match self {
            Self::V4(ret) => ret.get_header_len(),
            Self::V6(ret) => ret.get_header_len(),
            Self::ArpV4(_) => ARP_V4_HEADER_LEN,
            Self::Other(_) => 0,
        }
    }
    pub fn get_protocol(&self) -> isize {
        match self {
            Self::V4(ret) => ret.get_protocol() as isize,
            Self::V6(ret) => ret.get_protocol() as isize,
            Self::ArpV4(_) => -1,
            Self::Other(_) => -1,
        }
    }
}

#[derive(Debug, Clone, Copy)]
// 传输层协议枚举
pub enum TransportHeader {
    Tcp(TcpHeader),
    Udp(UdpHeader),
    Icmp(IcmpHeader),
    Other(isize),
}

impl fmt::Display for TransportHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            TransportHeader::Tcp(header) => write!(f, "{}", header),
            TransportHeader::Udp(header) => write!(f, "{}", header),
            TransportHeader::Icmp(header) => write!(f, "{}", header),
            _ => writeln!(f, ""),
        }
    }
}

impl FromPcap for TransportHeader {
    type Header = Self;
    fn from_pcap(
        flag: isize,
        pcap_index: usize,
        pcap_file: &mut PcapFile,
        offset: usize,
        header_len: usize,
    ) -> Result<TransportHeader, ErrorEnum> {
        let flag_type = TransportType::new(flag);
        match flag_type {
            // Tcp
            TransportType::Tcp => Ok(TransportHeader::Tcp(TcpHeader::from_pcap(
                0,
                pcap_index,
                pcap_file,
                offset,
                TCP_HEADER_LEN,
            )?)),
            // Udp
            TransportType::Udp => Ok(TransportHeader::Udp(UdpHeader::from_pcap(
                0,
                pcap_index,
                pcap_file,
                offset,
                UDP_HEADER_LEN,
            )?)),
            // 其他协议
            TransportType::Other => Ok(TransportHeader::Other(flag)),
        }
    }
    fn from_bytes(buf: &Vec<u8>) -> Result<Self::Header, ErrorEnum> {
        todo!()
    }
}

impl TransportHeader {
    pub fn get_header_len(&self) -> usize {
        match self {
            Self::Tcp(ret) => ret.get_header_len(),
            Self::Udp(_) => UDP_HEADER_LEN,
            Self::Icmp(_) => ICMP_HEADER_LEN,
            Self::Other(_) => 0,
        }
    }
    pub fn get_dst_port(&self) -> isize {
        match self {
            TransportHeader::Tcp(ret) => ret.dst_port as isize,
            TransportHeader::Udp(ret) => ret.dst_port as isize,
            TransportHeader::Icmp(_) => -1,
            TransportHeader::Other(_) => -1,
        }
    }
    pub fn get_src_port(&self) -> isize {
        match self {
            TransportHeader::Tcp(ret) => ret.src_port as isize,
            TransportHeader::Udp(ret) => ret.src_port as isize,
            TransportHeader::Icmp(_) => -1,
            TransportHeader::Other(_) => -1,
        }
    }
}

#[derive(Debug, Clone)]
// 应用层协议枚举
pub enum ApplicationHeader {
    Http(HttpHeader),
    Dns(DnsHeader),
    Other(isize),
}

impl fmt::Display for ApplicationHeader {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ApplicationHeader::Http(header) => write!(f, "{}", header),
            ApplicationHeader::Dns(header) => write!(f, "{}", header),
            _ => writeln!(f, ""),
        }
    }
}

impl FromPcap for ApplicationHeader {
    type Header = Self;

    fn from_pcap(
        flag: isize,
        pcap_index: usize,
        pcap_file: &mut PcapFile,
        offset: usize,
        header_len: usize,
    ) -> Result<Self::Header, ErrorEnum> {
        let flag_type = ApplicationType::new(flag);
        match flag_type {
            ApplicationType::Http => {
                let header_len = pcap_file
                    .get_single_pcap_mut(pcap_index)?
                    .pcap_record_hdr
                    .incl_len as usize
                    + PCAP_PRERECORD_HDR_SIZE
                    - offset;

                match HttpHeader::from_pcap(0, pcap_index, pcap_file, offset, header_len) {
                    Ok(ret) => Ok(ApplicationHeader::Http(ret)),
                    Err(_) => Ok(ApplicationHeader::Other(flag)),
                }
            }
            ApplicationType::Other => Ok(ApplicationHeader::Other(flag)),
            ApplicationType::Https => Ok(ApplicationHeader::Other(flag)),
        }
    }

    fn from_bytes(buf: &Vec<u8>) -> Result<Self::Header, ErrorEnum> {
        todo!()
    }
}

impl ApplicationHeader {
    fn get_header_len(&self) -> usize {
        match self {
            Self::Http(ret) => ret.get_header_len(),
            Self::Dns(_) => DNS_HEADER_LEN,
            Self::Other(_) => 0,
        }
    }
}

#[derive(Debug, Clone)]
// 完整的网络数据包表示（包含所有层）
pub struct NetworkPacket {
    pub eth_header: EthernetHeader,
    pub ip_header: IpHeader,                   // 使用枚举区分IPv4/IPv6
    pub transport_header: TransportHeader,     // 使用枚举区分TCP/UDP
    pub application_header: ApplicationHeader, // 使用枚举区分应用层协议
    pub payload: Vec<u8>,                      // 有效载荷
}

impl fmt::Display for NetworkPacket {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        // 直接调用各层协议的 Display 实现
        writeln!(f, "{}", self.eth_header)?;
        writeln!(f, "{}", self.ip_header)?;
        writeln!(f, "{}", self.transport_header)?;
        writeln!(f, "{}", self.application_header)?;

        if !self.payload.is_empty() {
            writeln!(f, "Payload Data ({} bytes):", self.payload.len())?;
            write!(f, "{}", format_data_as_lines(&self.payload, 4))?; // 显示前4行
        }

        Ok(())
    }
}

impl NetworkPacket {
    pub fn new_from_pcap(pcap_index: usize, pcap_file: &mut PcapFile) -> Result<Self, ErrorEnum> {
        let eth_header = EthernetHeader::from_pcap(
            0,
            pcap_index,
            pcap_file,
            PCAP_PRERECORD_HDR_SIZE,
            ETHERNET_HEADER_LEN,
        )?;

        let ip_header = IpHeader::from_pcap(
            eth_header.ether_type as isize,
            pcap_index,
            pcap_file,
            PCAP_PRERECORD_HDR_SIZE + ETHERNET_HEADER_LEN,
            0,
        );

        let ip_header = ip_header.unwrap_or_else(|e| {
            info!("{}", e.to_string());
            IpHeader::Other(0)
        });

        let transport_header = TransportHeader::from_pcap(
            ip_header.get_protocol(),
            pcap_index,
            pcap_file,
            ip_header.get_header_len() + ETHERNET_HEADER_LEN + PCAP_PRERECORD_HDR_SIZE,
            0,
        );

        let transport_header = transport_header.unwrap_or_else(|e| {
            info!("{}", e.to_string());
            TransportHeader::Other(0)
        });

        let application_header = ApplicationHeader::from_pcap(
            transport_header.get_dst_port(),
            pcap_index,
            pcap_file,
            ip_header.get_header_len()
                + ETHERNET_HEADER_LEN
                + PCAP_PRERECORD_HDR_SIZE
                + transport_header.get_header_len(),
            0,
        );
        let application_header = application_header.unwrap_or_else(|e| {
            info!("{}", e.to_string());
            ApplicationHeader::Other(0)
        });

        let single_pcap = pcap_file.get_single_pcap_mut(pcap_index)?;
        let mut payload = vec![
            0;
            single_pcap.pcap_record_hdr.incl_len as usize
                - ETHERNET_HEADER_LEN
                - ip_header.get_header_len()
                - transport_header.get_header_len()
                - application_header.get_header_len()
        ];

        pcap_file.pcap_file_buf.read_exact(&mut payload)?;
        Ok(Self {
            eth_header,
            ip_header,
            transport_header,
            application_header,
            payload,
        })
    }

    pub fn ethernet_type_eq(&self, ether_type: EtherType) -> bool {
        self.eth_header.ether_type == ether_type as u16
    }
    pub fn transport_type_eq(&self, transport_type: TransportType) -> bool {
        self.ip_header.get_protocol() == transport_type as isize
    }
    pub fn application_type_eq(&self, application_type: ApplicationType) -> bool {
        self.get_application_type() == application_type
    }
    pub fn ip_addr_eq(&self, ip_addr: &IpAddr) -> bool {
        if let IpAddr::V4(addr) = ip_addr {
            if let IpHeader::V4(ipv4_header) = &self.ip_header {
                return (ipv4_header.dst_addr == *addr) || (ipv4_header.src_addr == *addr);
            }
            if let IpHeader::ArpV4(arp_ipv4_header) = &self.ip_header {
                return (arp_ipv4_header.sender_ip == *addr)
                    || (arp_ipv4_header.target_ip == *addr);
            }
            return false;
        }
        if let IpAddr::V6(addr) = ip_addr {
            if let IpHeader::V6(ipv4_header) = &self.ip_header {
                return (ipv4_header.dst_addr == *addr) || (ipv4_header.src_addr == *addr);
            }
            return false;
        }
        false
    }
    pub fn mac_addr_eq(&self, mac_addr: &MacAddr) -> bool {
        self.eth_header.dst_mac == *mac_addr || self.eth_header.src_mac == *mac_addr
    }
    pub fn port_eq(&self, port: u16) -> bool {
        todo!()
    }

    pub fn get_ether_type(&self) -> EtherType {
        EtherType::new(self.eth_header.ether_type as isize)
    }
    pub fn get_transport_type(&self) -> TransportType {
        TransportType::new(self.ip_header.get_protocol())
    }

    pub fn get_application_type(&self) -> ApplicationType {
        ApplicationType::new(self.transport_header.get_dst_port())
    }
    pub fn get_ip_src_addr(&self) -> IpAddr {
        match &self.ip_header {
            IpHeader::V6(header) => IpAddr::V6(header.src_addr),
            IpHeader::V4(header) => IpAddr::V4(header.src_addr),
            IpHeader::ArpV4(header) => IpAddr::V4(header.sender_ip),
            IpHeader::Other(_) => IpAddr::Other(0),
        }
    }
    pub fn get_ip_dst_addr(&self) -> IpAddr {
        match &self.ip_header {
            IpHeader::V6(header) => IpAddr::V6(header.dst_addr),
            IpHeader::V4(header) => IpAddr::V4(header.dst_addr),
            IpHeader::ArpV4(header) => IpAddr::V4(header.target_ip),
            IpHeader::Other(_) => IpAddr::Other(0),
        }
    }
    pub fn get_src_mac(&self) -> MacAddr {
        self.eth_header.src_mac
    }
    pub fn get_dst_mac(&self) -> MacAddr {
        self.eth_header.dst_mac
    }
    pub fn get_dst_port(&self) -> isize {
        self.transport_header.get_dst_port()
    }
    pub fn get_src_port(&self) -> isize {
        self.transport_header.get_src_port()
    }
    pub fn get_length(&self) -> usize {
        ETHERNET_HEADER_LEN
            + self.ip_header.get_header_len()
            + self.ip_header.get_header_len()
            + self.transport_header.get_header_len()
            + self.application_header.get_header_len()
            + self.payload.len()
    }
}
